<template>
  <div>
    <el-input :value="form.batchName + ' / ' + form.taskName" placeholder="" size="small" clearable></el-input>

    <el-form ref="formRef" label-position="top" :model="form" :rules="rules" label-width="0">
      <el-row class="margin-top-20">
        <el-col :span="4" class="flex aic">
          <status-select v-model="form.status" @change="submitForm"> 当前状态 </status-select>
        </el-col>
        <el-col :span="4" class="flex aic">
          <el-form-item label="" size="normal" prop="taskHead" class="margin-bottom-0">
            <radio-select v-model="form.taskHead" :options="employeeList" key-name="employeeName" value-name="employeeId" @change="submitForm"
              >责任人</radio-select
            >
          </el-form-item>
        </el-col>
        <el-col :span="4" class="flex aic">
          <calendar-select v-model="form.planStart" disabled @change="submitForm">计划开始时间</calendar-select>
        </el-col>
        <el-col :span="4" class="flex aic">
          <calendar-select v-model="form.planFinish" disabled @change="submitForm">计划完成时间</calendar-select>
        </el-col>
        <el-col :span="4" class="flex aic">
          <calendar-select v-model="form.actualStart" @change="submitForm">实际开始时间</calendar-select>
        </el-col>
        <el-col :span="4" class="flex aic">
          <calendar-select v-model="form.actualFinish" @change="submitForm">实际结束时间</calendar-select>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" class="margin-top-20">
        <el-tab-pane name="taskInfo">
          <template #label> <i class="el-icon-document-checked"></i> 任务信息 </template>
          <div>任务详情：</div>
          <template v-if="!remarkOpen">
            <div v-if="form.remark" class="margin-top-15">
              {{ form.remark }}
              <span class="font-color-primary margin-left-10 cursor-point" @click="remarkOpen = true">编辑</span>
            </div>
            <div v-else class="margin-top-15">
              --暂无描述--
              <span class="font-color-primary margin-left-10 cursor-point" @click="remarkOpen = true">添加描述</span>
            </div>
          </template>
          <template v-else>
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="20"
              resize="none"
              placeholder=""
              :maxlength="-1"
              :show-word-limit="false"
              :autosize="{ minRows: 2, maxRows: 4 }"
              class="margin-top-10"
            ></el-input>
            <el-button-group class="margin-top-5 float-right">
              <el-button
                type="primary"
                size="small"
                @click="
                  submitForm();
                  remarkOpen = false;
                "
                >确定</el-button
              >
              <el-button type="primary" plain size="mini" @click="remarkOpen = false">取消</el-button>
            </el-button-group>
          </template>

          <div class="margin-top-30">人员信息：</div>
          <multiple-select
            v-model="selectEmployeeList"
            :options="employeeList"
            key-name="employeeName"
            value-name="employeeId"
            class="margin-top-15"
            @change="handleTaskEmployeeChange"
          ></multiple-select>

          <div class="flex aic margin-top-15 margin-bottom-15">
            <span class="fwb flexnone padding-right-5 font-weight-bold font-size-15">操作信息</span>
            <div class="height-1 flex1" style="background: #dcdfe6"></div>
          </div>
          <div class="height-150 overflow-auto">
            <div v-for="(item, index) in logList" :key="index" class="line-height-30">
              {{ item.createTime }} ， 由<span class="font-color-warning font-weight-bold padding-lr-5">{{ item.operName }}</span
              ><span>{{ item.operDes }}</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane name="costEmployee">
          <template #label> <i class="el-icon-user"></i> 人工工时 </template>
          <cost-employee :task-id="taskId" @log="getLoglist"></cost-employee>
        </el-tab-pane>
        <!-- ... other tab panes ... -->
      </el-tabs>
    </el-form>
  </div>
</template>

<script setup name="TaskDetail" lang="ts">
import { ref, reactive, watch, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getBatchTask, addBatchTask, updateBatchTask } from '@/api/agriculture/batchTask';
import { listCropBatch } from '@/api/agriculture/cropBatch';
import { listUser } from '@/api/system/user';
import { listLand } from '@/api/agriculture/land';
import { listTaskLog, addLog } from '@/api/agriculture/taskLog';
import { listData } from '@/api/system/dict/data';
import { listTaskEmployee, addTaskEmployee, delTaskEmployeeByTaskIdAndEmployeeId } from '@/api/agriculture/taskEmployee';
import RadioSelect from '@/views/components/RadioSelect/index.vue';
import CalendarSelect from '../CalendarSelect/index.vue';
import MultipleSelect from '../MultipleSelect/index.vue';
import StatusSelect from '../StatusSelect/index.vue';
import CostEmployee from './CostEmployee.vue';
import CostMachine from './CostMachine.vue';
import CostMaterial from './CostMaterial.vue';

const props = defineProps({
  taskId: {
    type: Number
  },
  oprType: {
    type: String,
    default: ''
  },
  batchId: {
    type: Number
  }
});

const emit = defineEmits(['update:modelValue']);

const activeName = ref('taskInfo');
const batchList = ref([]);
const userList = ref([]);
const landList = ref([]);
const batchTaskStatusList = ref([]);
const selectEmployeeList = ref([]);
const employeeList = ref([]);
const logList = ref([]);
const remarkOpen = ref(false);
const form = reactive({
  // ... your form data here
});
const rules = ref({
  // ... your form validation rules here
});

const formRef = ref(null);

watch(
  () => props.oprType,
  (n, o) => {
    if (n.includes('add')) {
      handleAdd();
    } else if (n.includes('update')) {
      handleUpdate();
    }
  },
  { immediate: true }
);

watch(
  () => form.taskHead,
  (n) => {
    console.log('taskHead', n);
    let arr = employeeList.value.filter((item) => item.employeeId == n);
    if (arr.length > 0) {
      form.taskHeadName = arr[0].employeeName;
    }
  }
);

onMounted(() => {
  getBatchList();
  getUserList();
  getLandList();
  getBatchTaskStatusList();
  getLoglist();
  getEmployeeList();
  getTaskEmployee();
});

const getBatchList = async () => {
  batchList.value = (await listCropBatch()).rows;
};

const getUserList = async () => {
  userList.value = (await listUser()).rows;
};

const getEmployeeList = async () => {
  employeeList.value = (await listEmployee()).rows;
};

const getLandList = async () => {
  landList.value = (await listLand()).rows;
};

const getTaskEmployee = async () => {
  const { rows } = await listTaskEmployee({ taskId: props.taskId });
  selectEmployeeList.value = rows.map((item) => item.employeeId);
};

const getLoglist = async () => {
  logList.value = (await listTaskLog({ taskId: props.taskId })).rows;
};

const getBatchTaskStatusList = async () => {
  batchTaskStatusList.value = (await listData({ dictType: 'agriculture_batch_task_status' })).rows;
};

const reset = () => {
  // Reset your form here
};

const handleAdd = () => {
  reset();
  // Additional logic for adding
};

const handleUpdate = () => {
  reset();
  const taskId = props.taskId;
  getBatchTask(taskId).then((response) => {
    Object.assign(form, response.data);
  });
};

const addTaskLog = async (des) => {
  await addLog({ taskId: props.taskId, operDes: des });
  getLoglist();
};

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (form.taskId) {
        await updateBatchTask(form);
        await addTaskLog('完善任务信息');
        ElMessage.success('修改成功');
      } else {
        await addBatchTask(form);
        ElMessage.success('新增成功');
      }
    }
  });
};

const handleTaskEmployeeChange = (e) => {
  const { type, value } = e;
  if (type === 'add') {
    addTaskEmployee({ taskId: props.taskId, employeeId: value }).then(() => {
      addTaskLog('增加参与人员');
      ElMessage.success('添加成功');
    });
  } else if (type === 'del') {
    delTaskEmployeeByTaskIdAndEmployeeId(props.taskId, value).then(() => {
      addTaskLog('删除参与人员');
      ElMessage.success('删除成功');
    });
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
}
</style>
